package service

import (
	"github.com/honwee/awm/internal/model"
	"github.com/honwee/awm/internal/repository"
	"time"
)

type WorkflowRunService struct {
	workflowRunRepo *repository.WorkflowRunRepository
}

func NewWorkflowRunService(workflowRunRepo *repository.WorkflowRunRepository) *WorkflowRunService {
	return &WorkflowRunService{
		workflowRunRepo: workflowRunRepo,
	}
}

// CreateWorkflowRun 创建工作流运行记录
func (s *WorkflowRunService) CreateWorkflowRun(run *model.WorkflowRun) error {
	run.Status = model.StatusRunning
	run.StartedAt = time.Now()
	return s.workflowRunRepo.Create(run)
}

// UpdateWorkflowRun 更新工作流运行记录
func (s *WorkflowRunService) UpdateWorkflowRun(workflowRunID string, status string, finishedAt *time.Time) error {
	if status == model.StatusSucceeded || status == model.StatusFailed {
		if finishedAt == nil {
			now := time.Now()
			finishedAt = &now
		}
		return s.workflowRunRepo.UpdateStatusWithFinishedAt(workflowRunID, status, finishedAt)
	}
	return s.workflowRunRepo.UpdateStatus(workflowRunID, status)
}

// GetWorkflowRun 获取工作流运行记录
func (s *WorkflowRunService) GetWorkflowRun(workflowRunID string) (*model.WorkflowRun, error) {
	return s.workflowRunRepo.FindByWorkflowRunID(workflowRunID)
}

// GetUserWorkflowRuns 获取用户的工作流运行记录
func (s *WorkflowRunService) GetUserWorkflowRuns(userID string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	return s.workflowRunRepo.FindByUserID(userID, offset, limit)
}

// GetWorkflowRunsByStatus 获取指定状态的工作流运行记录
func (s *WorkflowRunService) GetWorkflowRunsByStatus(status string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	return s.workflowRunRepo.FindByStatus(status, offset, limit)
}

// GetWorkflowRuns 获取工作流的运行记录
func (s *WorkflowRunService) GetWorkflowRuns(workflowID string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	return s.workflowRunRepo.FindByWorkflowID(workflowID, offset, limit)
}

// UpdateWorkflowRunStatus 更新工作流运行状态
func (s *WorkflowRunService) UpdateWorkflowRunStatus(workflowRunID string, status string) error {
	return s.workflowRunRepo.UpdateStatus(workflowRunID, status)
}
